#include "QiniuManager.h"
#include <QDebug>
#include <QFileInfo>

QiniuManager::QiniuManager(QObject *parent)
    : QObject(parent)
    , m_uploader(nullptr)
{
}

QiniuManager::~QiniuManager()
{
    if (m_uploader) {
        delete m_uploader;
        m_uploader = nullptr;
    }
}

bool QiniuManager::init(const QString &accessKey,
                       const QString &secretKey,
                       const QString &bucket,
                       const QString &zone)
{
    // 如果已初始化，先清理旧的上传器
    if (m_uploader) {
        delete m_uploader;
        m_uploader = nullptr;
    }

    // 创建新的上传器
    m_uploader = new QiniuUploader(accessKey, secretKey, bucket, zone, this);

    // 连接信号
    connect(m_uploader, &QiniuUploader::uploadProgress, this, [this](int percent) {
        emit uploadProgress(m_currentUploadingFile, percent);
    });

    connect(m_uploader, &QiniuUploader::uploadFinished, this,
        [this](const QString &key, const QString &url) {
            // 保存上传成功的图片信息
            m_uploadedImages.append(qMakePair(key, url));
            emit uploadFinished(m_currentUploadingFile, key, url);
            m_currentUploadingFile.clear();
        });

    connect(m_uploader, &QiniuUploader::uploadError, this,
        [this](const QString &errorMsg) {
            emit uploadError(m_currentUploadingFile, errorMsg);
            m_currentUploadingFile.clear();
        });

    return true;
}

bool QiniuManager::uploadImage(const QString &filePath)
{
    if (!m_uploader) {
        emit uploadError(filePath, "七牛云上传器未初始化");
        return false;
    }

    // 检查文件类型，只允许上传图片
    QFileInfo fileInfo(filePath);
    QString suffix = fileInfo.suffix().toLower();
    QStringList allowedSuffixes = {"jpg", "jpeg", "png", "gif", "bmp", "webp"};

    if (!allowedSuffixes.contains(suffix)) {
        emit uploadError(filePath, "不支持的图片格式");
        return false;
    }

    // 设置当前上传文件路径
    m_currentUploadingFile = filePath;

    // 开始上传
    return m_uploader->uploadFile(filePath);
}

QList<QPair<QString, QString>> QiniuManager::getUploadedImages() const
{
    return m_uploadedImages;
}
